package com.example.stock.schedule;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Console;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.stock.entity.Stock;
import com.example.stock.service.IStockService;
import com.example.stock.service.LastMaxStockService;
import com.example.stock.service.VolumeCompareService;
import com.example.stock.tencent.DingDingBot;
import com.example.stock.tencent.StockBean;
import com.example.stock.tencent.TencentProxy;
import com.example.stock.util.HolidayUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.text.ParseException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author tanlvxu
 * @Date 2024/12/18 17:19
 * @Description 获取数据任务
 */
@Service
@EnableScheduling
public class GetDataTask {

    @Autowired
    private TencentProxy tencentProxy;

    @Autowired
    private IStockService iStockService;

    @Autowired
    private VolumeCompareService volumeCompareService;

    @Scheduled(cron = "30 25 9 * * 1-5")
    public void refresh1() throws ParseException {
        if(!isJiaoyiDay()){
            return ;
        }
        Console.log("9.25开始刷新数据");
        List<StockBean> stockBeans = tencentProxy.getData();
        Date now = DateUtil.date();
        List<Stock> stocks = new ArrayList<>();
        for (int i = 0; i < stockBeans.size(); i++) {
            StockBean stockBean = stockBeans.get(i);
            Stock stock = new Stock();
            BeanUtil.copyProperties(stockBean, stock,"time");
            stock.setCalcTime(now);
            stock.setCalcType(1);
            stocks.add(stock);
        }
        iStockService.saveBatch(stocks);
        try {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            // 格式化当前时间
            String curDay =  LocalDateTime.now().format(formatter);
            volumeCompareService.volumeCompare2111(stockBeans,curDay);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            // 格式化当前时间
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            // 格式化当前时间
            String curDay =  LocalDateTime.now().format(formatter);
            volumeCompareService.volumeCompare2(stockBeans,curDay);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Console.log("9.25结束刷新数据");
    }

    @Scheduled(cron = "30 30 11 * * 1-5")
    public void refresh2() throws ParseException {
        if(!isJiaoyiDay()){
            return ;
        }
        Console.log("9.25开始刷新数据");
        List<StockBean> stockBeans = tencentProxy.getData();

        Date now = DateUtil.date();
        List<Stock> stocks = new ArrayList<>();
        for (int i = 0; i < stockBeans.size(); i++) {
            StockBean stockBean = stockBeans.get(i);
            Stock stock = new Stock();
            BeanUtil.copyProperties(stockBean, stock,"time");
            stock.setCalcTime(now);
            stock.setCalcType(2);
            stocks.add(stock);
        }
        iStockService.saveBatch(stocks);
        Console.log("9.25结束刷新数据");
    }

    private boolean isJiaoyiDay() throws ParseException {
        // 获取当前时间
        LocalDateTime nowLocal = LocalDateTime.now();
        // 定义日期时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        // 格式化当前时间
        String formattedNow = nowLocal.format(formatter);
        String workingDay = HolidayUtil.isWorkingDay(formattedNow);
        if(!"0".equals(workingDay)){
            Console.log(formattedNow+"不是工作日不处理refresh3");
            return false;
        }
        return true;
    }

    @Scheduled(cron = "30 00 15 * * 1-5")
    public void refresh3() throws ParseException {
          if(!isJiaoyiDay()){
              return ;
          }
        Date now = DateUtil.date();
        Console.log(now+"开始刷新数据");
        List<StockBean> stockBeans = tencentProxy.getData();
        List<Stock> stocks = new ArrayList<>();
        for (int i = 0; i < stockBeans.size(); i++) {
            StockBean stockBean = stockBeans.get(i);
            Stock stock = new Stock();
            BeanUtil.copyProperties(stockBean, stock,"time");
            stock.setCalcTime(now);
            stock.setCalcType(3);
            stocks.add(stock);
        }
        iStockService.saveBatch(stocks);
//        anylysisP(stockBeans);
        //分析情况
        Console.log(now+"结束刷新数据");
    }

//    @PostConstruct
    public void notityVolunmeCompare(){
        try {
            List<StockBean> stockBeans = new ArrayList<>();
            // 获取当前时间
            LocalDateTime nowLocal = LocalDateTime.now();
            // 定义日期时间格式
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            // 格式化当前时间
            String formattedNow = nowLocal.format(formatter);
            String workingDay = HolidayUtil.isWorkingDay(formattedNow);
            Date date = Date.from(nowLocal.atZone(ZoneId.systemDefault()).toInstant());
            Date dayBegin = com.example.stock.util.DateUtil.getDayBegin(date);
            Date dayEnd = com.example.stock.util.DateUtil.getDayEnd(date);
            List<Stock> list1 = iStockService.list(Wrappers.<Stock>lambdaQuery().eq(Stock::getCalcType, 1).ge(Stock::getCalcTime, dayBegin).le(Stock::getCalcTime, dayEnd));

            for (Stock stock : list1){
                StockBean stockBean = new StockBean();
                BeanUtil.copyProperties(stock,stockBean);
                stockBeans.add(stockBean);
            }

            volumeCompareService.volumeCompare(stockBeans);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    public void anylysisP(List<StockBean> resultArr){
        List<StockBean> highArr = new ArrayList<>();
        resultArr.forEach(obj->{
            if(obj.getPriceNow() == obj.getHighLimit()){
                highArr.add(obj);
            }
        });
        StringBuilder stringBuilder = new StringBuilder();
        String title = "### **今日共涨停"+highArr.size()+"只股票**\n" ;
        stringBuilder.append(title);
        for (int i = 0; i < highArr.size(); i++) {
            StockBean stockBean = highArr.get(i);
            stringBuilder.append(String.format("- %s-%s\n",stockBean.getName(),stockBean.getCode()));
        }
        DingDingBot.sendMarkDown(title,stringBuilder.toString());
    }

}
